<template>
  <div class="article-container">
    <!-- 导航栏 -->
    <van-nav-bar
        class="page-nav-bar"
        title="黑马头条"
    >
        <van-icon slot="left" name="arrow-left" @click="$router.push('/')"></van-icon>
    </van-nav-bar>
    <!-- 导航栏 -->
    <div class="main-wrap">
        <!-- 加载中 -->
        <div class="loading-wrap" v-if="isloading">
            <van-loading
                color="#3296fa"
                vertical
            >加载中</van-loading>
        </div>
        <!-- 加载中 -->
        <!-- /加载完成-文章详情 -->
        <!-- 注意v-if有了article才被渲染出来 -->
        <div class="article-detail markdown-body" v-else-if="article.title">
            <!-- 文章标题 -->
            <h1 class="article-title">{{article.title}}</h1>
            <!-- 文章标题 -->
            <!-- 用户信息 -->
            <van-cell class="user-info" center :border="false">
                <van-image
                    class="avatar"
                    slot="icon"
                    round
                    fit="cover"
                    :src="article.aut_photo"
                />
                <div slot="title" class="user-name">{{article.aut_name}}</div>
                <div slot="label" class="publish-date">{{article.pubdate|RelativeTime}}</div>
                <!-- 模板中的$event是事件参数
                当我们传递给子组件的数据既要使用还要修改的时候
                    传递 props
                        :isFollow="article.is_followed"
                    修改: 自定义事件
                        @update-is_followed="article.is_followed=$event"
                    简写方式: 在组件上使用v-model
                        value="article.is_followed"
                        @input="update-is_followed"
                    如果需要修改v-model的默认规则名称,可以使用子组件的model属性 -->
                <!-- <followUser :isFollow="article.is_followed" :userId="article.aut_id" @update-is_followed="article.is_followed=$event"/> -->
                <followUser  :userId="article.aut_id" v-model="article.is_followed" class="follow-btn"/>
            </van-cell>
            <!-- 用户信息 -->
            <!-- 文章内容 -->
            <div class="article-content" v-html="article.content" ref="articleContent"></div>
            <van-divider>正文结束</van-divider>
            <!-- 文章评论列表 -->
            <commentList  @replyClick="replyClick" :list="commentList" :source="article.art_id" @onload-success="total=$event.total_count"/>
            <!-- 文章评论列表 -->
            <!-- /底部区域 -->
            <div class="article-bottom">
                <van-button
                    class="comment-btn"
                    type="default"
                    round
                    size="small"
                    @click="isShowPopup=true"
                >写评论</van-button>
                <van-icon
                    name="comment-o"
                    :info="total"
                    color="#777"
                />
                <!-- 收藏组件 -->
                <collectArticle
                    :isCollected="article.is_collected"
                    :articleId="article.art_id"
                    @update-is_collected="article.is_collected=$event"
                    class="btn-item"
                />
                <likeArticle
                 class="btn-item"
                :isliked="article.attitude"
                :articleId="article.art_id"
                @update-is_liked="article.attitude=$event"/>
                <van-icon name="share" color="#777777"></van-icon>
            </div>
             <!-- /底部区域 -->
            <!-- 回复弹出层 -->
            <van-popup v-model="isShowPopup" position="bottom">
                <CommentPost @successPost="successPost" class="comment-post" :target="(article.art_id.c&&article.art_id.c.join(''))||article.art_id"/>
            </van-popup>
        </div>
        <!-- /加载完成-文章详情 -->
        <!-- /加载失败：404 -->
        <div class="error-wrap" v-else-if="errorStatus===404">
            <van-icon name="failure" />
            <p class="text">该资源不存在或已删除！</p>
        </div>
        <!-- /加载失败：404 -->
        <!-- /加载失败：其它未知错误（例如网络原因或服务端异常） -->
        <div class="error-wrap" v-else>
            <van-icon name="failure" />
            <p class="text">内容加载失败！</p>
            <van-button class="retry-btn" @click="loadArticle()">点击重试</van-button>
        </div>
        <!-- /加载失败：其它未知错误（例如网络原因或服务端异常） -->
    </div>
    <!-- 评论回复 -->
    <van-popup v-model="isReplayShow" style="height: 100%" position="bottom">
        <CommentReply :comment="currentCommet" :close.sync="isReplayShow" v-if="isReplayShow"/>
    </van-popup>
    <!-- 评论回复 -->
  </div>
</template>

<script>
import { getArticleById } from '@/api/article'
import { ImagePreview } from 'vant'
import followUser from '@/components/follow-user'
import collectArticle from '@/components/collect-article'
import likeArticle from '@/components/like-article'
import commentList from './components/comment-list'
import CommentPost from './components/comment-post'
import CommentReply from './components/comment-reply'
export default {
  name: 'ArticleIndex',
  components: {
    followUser,
    collectArticle,
    likeArticle,
    commentList,
    CommentPost,
    CommentReply
  },
  provide: function () {
    return {
      articleId: this.articleId
    }
  },
  props: {},
  data () {
    return {
      // 控制加载中
      isloading: true,
      errorStatus: 0,
      article: {},
      articleId: this.$route.params.articleId,
      total: 0,
      isShowPopup: false,
      isReplayShow: false,
      commentList: [],
      currentCommet: {}
    }
  },
  computed: {},
  watch: {},
  created () {
    this.loadArticle()
    console.log(this.article.is_followed)
  },
  mounted () {},
  methods: {
    async loadArticle () {
      try {
        const { data } = await getArticleById(this.articleId)
        // 测试内容加载失败
        // if (Math.random() > 0.2) {
        //   JSON.parse('djslah')
        // }
        this.article = data.data
        // 有了条件渲染和加载中图片要用定时器
        setTimeout(() => {
          console.log(this.$refs.articleContent)
          this.PreviewImg()
        }, 0)
      } catch (err) {
        if (err.response && err.response.status === 400) {
          this.errorStatus = 404
        }
      }
      this.isloading = false
    },
    PreviewImg () {
      const imgArr = (this.$refs.articleContent && this.$refs.articleContent.querySelectorAll('img')) || []
      const images = []
      imgArr.forEach((img, index) => {
        images.push(img.src)
        img.onclick = function () {
          console.log(index)
          ImagePreview({
            images,
            startPosition: index
          })
        }
      })
    },
    // 发布评论子组件所要调取的函数
    successPost ($event) {
    // 关闭弹出层
      this.isShowPopup = false
      // 将内容显示到评论顶部
      this.commentList.unshift($event)
    },
    replyClick (comment) {
      this.currentCommet = comment
      this.isReplayShow = true
    }
  }
}
</script>

<style scoped lang="less">
@import url('./github-markdown.css');
.article-container{
    background-color: #fff;
    /deep/.page-nav-bar{
        i.van-icon-arrow-left{
            color: #fff;
        }
    }
    /deep/.main-wrap{
        position: fixed;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        overflow-y: scroll;
        background-color: #fff;
        .article-detail{
            position: fixed;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            top: 92px;
            bottom: 88px;
            overflow-y: scroll;
            background-color: #fff;
            .article-title{
                font-size: 40px;
                padding: 50px 32px;
                margin: 0;
                color: #3a3a3a;
            }
            .user-info{
                .avatar{
                    width: 70px;
                    height: 70px;
                    margin-right: 17px;
                }
                .follow-btn{
                    width: 170px;
                    height: 60px;
                }
            }
            .article-content{
                width: 100%;
                height: auto;
                padding: 45px 32px;
                font-size: 32px;
            }
        }
    }
    .loading-wrap {
        padding: 200px 32px;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #fff;
    }

    .error-wrap {
        // position: relative;
        // z-index: 1;
        padding: 200px 32px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        background-color: #fff;
        .van-icon {
            font-size: 122px;
            color: #b4b4b4;
        }
        .text {
            font-size: 30px;
            color: #666666;
            margin: 33px 0 46px;
        }
        .retry-btn {
            width: 280px;
            height: 70px;
            line-height: 70px;
            border: 1px solid #c3c3c3;
            font-size: 30px;
            color: #666666;
        }
    }
    /deep/.article-bottom{
        background-color: #fff;
        position: fixed;
        bottom: 0;
        left: 0;
        width: 750px;
        height: 88px;
        display: flex;
        justify-content: space-around;
        align-items: center;
        border-top: 1px solid #eee;
        .van-button__text{
            font-size: 30px;
            color: #a7a7a7;
        }
        .comment-btn{
            width: 282px;
            height: 46px;
            font-size: 23px;
        }
        i.van-icon{font-size: 40px;}
        .btn-item {
            border: none;
            padding: 0;
            height: 40px;
            line-height: 40px;
            color: #777777
        }
    }
}
</style>
